/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.csource.manage.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.dto.FileInfoSaveDto;
import com.icinfo.cloud.provider.common.enums.AttachmentRequestContentTypeEnum;
import com.icinfo.cloud.provider.common.enums.FileTransferFormEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.oss.service.IOssOperateService;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.CustomCheckParamUtil;
import com.icinfo.cloud.provider.peripheralinterface.regulatory.service.IRegulatoryService;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.dto.DingUserResultDto;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.dto.OrgInfoResultDto;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.approval.vo.LineTerritoryInfoVo;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.csource.manage.dto.*;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceEnum;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceOperateTypeEnum;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceStatusEnum;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceMaterialRecordMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourcePartyInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterDetailInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterMainInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.*;
import com.icinfo.cloud.provider.punish.csource.manage.service.*;
import com.icinfo.cloud.provider.punish.evideinv.dto.CaseSourceEventSaveDto;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.external.cadjjbxx.service.impl.ExternalService;
import com.icinfo.cloud.provider.punish.external.dto.EntBaseInfoDto;
import com.icinfo.cloud.provider.punish.external.vo.EntBaseInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.AppendixDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.AttachmentTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseReasonMainRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseReasonMainRecord;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseReasonInfoDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseRegisterSaveDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.service.ICaseRegisterService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 外部应用案源操作接口实现类
 *
 * @author zhengqiang
 * @date 2022年08月15日
 */
@Slf4j
@Service
public class CaseSourceApiServiceImpl extends MyBatisServiceSupport implements ICaseSourceApiService {

    private static final Logger logger = LoggerFactory.getLogger(CaseSourceApiServiceImpl.class);

    @Resource
    private CaseSourceRegisterMainInfoMapper caseSourceRegisterMainInfoMapper;
    @Resource
    private CaseSourcePartyInfoMapper caseSourcePartyInfoMapper;
    @Resource
    private CaseSourceRegisterDetailInfoMapper caseSourceRegisterDetailInfoMapper;
    @Resource
    private ICaseRegisterService caseRegisterService;
    @Resource
    private ICaseSourceFlowRecordService caseSourceFlowRecordService;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private IRegulatoryService regulatoryService;
    @Resource
    private ICaseSourcePartyInfoService caseSourcePartyInfoService;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private ICaseSourceRegisterMainInfoService caseSourceRegisterMainInfoService;
    @Resource
    private CaseSourceMaterialRecordMapper caseSourceMaterialRecordMapper;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private ExternalService externalService;
    @Resource
    private ICaseSourceHandlePersonRecordService caseSourceHandlePersonRecordService;
    @Resource
    private IOssOperateService iOssOperateService;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Value("${taskCenter.url}")
    private String taskCenterUrl;


    /**
     * 描述： 保存外部应用案源登记信息
     *
     * @author: zhengqiang
     * @date: 2022/8/15
     * @param: saveDto
     * @return {@link Result}
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveCaseSourceRegisterOfApp(CaseSourceRegisterOfAppSaveDto saveDto) {
        log.info("案源登记saveCaseSourceRegisterOfApp 请求参数:{}", JSON.toJSONString(saveDto));
        //参数校验
        checkCaseSourceParams(saveDto);

        //案源id处理
        dealCaseSourceId(saveDto);
        //当事人处理
        dealCaseSourcePartyInfo(saveDto);
        //案源主信息处理
        dealCaseSourceMainInfo(saveDto);
        //检查数据处理
        dealCaseSourceCheckInfo(saveDto);
        //案由处理
        dealCaseSourceReasonInfo(saveDto);
        //证据材料处理
        dealCaseSourceMaterialRecord(saveDto);
        //保存流转记录
        saveCaseSourceFlowRecord(saveDto);
        caseSourceRegisterMainInfoService.saveCaseSourceRegisterDoc(saveDto.getCaseSourceId(),saveDto.getCaseSourceOperateType(),null);
        //新增案源事件-证据端
        this.saveCaseSourceEvent(saveDto.getCaseSourceName(), saveDto.getCaseSourceId());
        return Result.success(Constant.STRING_SUCCESS_CH, saveDto.getCaseSourceId());
    }

    /**
     * 同步证据端案源事件
     *
     * @param caseSourceName
     * @param caseSourceId
     * @return
     */
    private void saveCaseSourceEvent(String caseSourceName, String caseSourceId) {
        try {
            CaseSourceEventSaveDto dto = new CaseSourceEventSaveDto();
            dto.setCaseSourceId(caseSourceId);
            dto.setCaseSourceName(caseSourceName);
            evidenceInventoryService.saveCaseSourceEvent(dto);
        } catch (Exception e) {
            logger.error("新增案源事件失败", e);
        }
    }

    /**
     * 案源id处理
     *
     * @param saveDto
     */
    private void dealCaseSourceId(CaseSourceRegisterOfAppSaveDto saveDto) {
        String caseSourceId = BaseUtil.createUid();
        //查询案源信息是否已存在
        Example query = new Example(CaseSourceRegisterMainInfo.class);
        query.createCriteria().andEqualTo("caseSourceAppServiceId", saveDto.getCaseSourceRegisterId()).andEqualTo("caseSourceAppId", saveDto.getCaseSourceAppId());
        List<CaseSourceRegisterMainInfo> caseSourceRegisterMainInfos = caseSourceRegisterMainInfoMapper.selectByExample(query);
        if (!ObjectUtils.isEmpty(caseSourceRegisterMainInfos)) {
            caseSourceId = caseSourceRegisterMainInfos.get(0).getId();
        }
        saveDto.setCaseSourceId(caseSourceId);
    }

    /**
     * 案源当事人处理
     */
    private void dealCaseSourcePartyInfo(CaseSourceRegisterOfAppSaveDto saveDto) {
        //当事人校验
        List<CaseSourcePartyInfoSaveDto> caseSourcePartyInfoDtoList = saveDto.getCaseSourcePartyInfoDtoList();
        if (!ObjectUtils.isEmpty(caseSourcePartyInfoDtoList)) {
            //删除案源当事人数据
            Example delExample = new Example(CaseSourcePartyInfo.class);
            delExample.createCriteria().andEqualTo("caseSourceId", saveDto.getCaseSourceId());
            caseSourcePartyInfoMapper.deleteByExample(delExample);

            caseSourcePartyInfoDtoList.forEach(party -> {
                CaseSourcePartyInfo caseSourcePartyInfo = new CaseSourcePartyInfo();
                BeanUtils.copyProperties(party, caseSourcePartyInfo);
                caseSourcePartyInfo.setId(BaseUtil.createUid());
                caseSourcePartyInfo.setCaseSourceId(saveDto.getCaseSourceId());
                caseSourcePartyInfo.setStatus(Constant.STRING_1);//有效
                caseSourcePartyInfo.setAddress(caseSourcePartyInfo.getAddressDetail());
                //当事人详情地址设置
                if (PartyTypeEnum.PERSON.getCode().equals(party.getPartyType())) {
                    if (!ObjectUtils.isEmpty(caseSourcePartyInfo.getAddressAreas())) {
                        String addressAreasStr = caseSourcePartyInfo.getAddressAreas().replace(",", "");
                        String addressDetail = caseSourcePartyInfo.getAddressDetail();
                        caseSourcePartyInfo.setAddress(addressAreasStr + addressDetail);
                    } else {
                        caseSourcePartyInfo.setAddress(caseSourcePartyInfo.getAddressDetail());
                    }

                }
                //当事人为企业,法人证件号为空,调用接口补充法人证件号
                if (PartyTypeEnum.LEGAL.getCode().equals(party.getPartyType())
                        && (ObjectUtils.isEmpty(party.getLegalCertNo()) || ObjectUtils.isEmpty(party.getPartyIdentityCode())) ) {
                    EntBaseInfoDto entBaseInfoDto = new EntBaseInfoDto();
                    if (!ObjectUtils.isEmpty(party.getPartyIdentityCode())) {
                        entBaseInfoDto.setTyxydm(party.getPartyIdentityCode());
                    }

                    if (ObjectUtils.isEmpty(party.getPartyIdentityCode()) && !ObjectUtils.isEmpty(party.getPartyName())) {//社会信用代码为空使用企业名称
                        entBaseInfoDto.setFrmc(party.getPartyName());
                    }
                    EntBaseInfoVo entBaseInfo = externalService.getEntBaseInfo(entBaseInfoDto);
                    if (!ObjectUtils.isEmpty(entBaseInfo)) {
                        if (ObjectUtils.isEmpty(party.getLegalCertNo())) {
                            caseSourcePartyInfo.setLegalCertNo(entBaseInfo.getFrZjhm());
                        }
                        if (ObjectUtils.isEmpty(party.getPartyIdentityCode())) {
                            caseSourcePartyInfo.setPartyIdentityCode(entBaseInfo.getTyxydm());
                        }
                    }
                }
                caseSourcePartyInfoMapper.insertSelective(caseSourcePartyInfo);
            });
        }
    }

    /**
     * 案源主信息处理
     */
    private void dealCaseSourceMainInfo(CaseSourceRegisterOfAppSaveDto saveDto) {
        boolean isSave = false;
        //查询案源信息是否已存在
        CaseSourceRegisterMainInfo mainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(saveDto.getCaseSourceId());
        if (ObjectUtils.isEmpty(mainInfo)) {
            isSave = true;
            mainInfo = new CaseSourceRegisterMainInfo();
        }

        //案源主信息处理
        BeanUtils.copyProperties(saveDto, mainInfo);
        String caseSourceOperateType = saveDto.getCaseSourceOperateType();
        if (CaseSourceOperateTypeEnum.APPOINT.getCode().equals(caseSourceOperateType)) {
            //指派
            mainInfo.setCaseSourceStatus(CaseSourceStatusEnum.PRE_SURVEY.getIndex());
            mainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_AYZP);
            //保存案源办案人员信息
            CaseSourceHandlePersonRecordSaveDto caseSourceHandlePersonRecordSaveDto = new CaseSourceHandlePersonRecordSaveDto();
            BeanUtils.copyProperties(saveDto, caseSourceHandlePersonRecordSaveDto);
            caseSourceHandlePersonRecordSaveDto.setCaseSourceId(saveDto.getCaseSourceId());
            caseSourceHandlePersonRecordSaveDto.setHandlePersonId(saveDto.getHandlePersonMainId());
            caseSourceHandlePersonRecordSaveDto.setHandlePersonName(saveDto.getHandlePersonMainName());
            caseSourceHandlePersonRecordSaveDto.setHandlePersonType(Constant.STRING_1);
            caseSourceHandlePersonRecordService.saveCaseSourceHandlePersonRecord(caseSourceHandlePersonRecordSaveDto);
            caseSourceHandlePersonRecordSaveDto.setHandlePersonId(saveDto.getHandlePersonAssistId());
            caseSourceHandlePersonRecordSaveDto.setHandlePersonName(saveDto.getHandlePersonAssistName());
            caseSourceHandlePersonRecordSaveDto.setHandlePersonType(Constant.STRING_2);
            caseSourceHandlePersonRecordService.saveCaseSourceHandlePersonRecord(caseSourceHandlePersonRecordSaveDto);

        } else {
            //登记
            mainInfo.setCaseSourceStatus(CaseSourceStatusEnum.TO_DISPATCH.getIndex());
            mainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_AYDJ);
        }
        //根据案件来源获取对应数据
        String caseSourceDesc = "";
        String case_source = saveDto.getCaseSource();
        if (CaseSourceEnum.CASE_SOURCE_SHJB.getCode().equals(case_source)) {
            //社会举报
            if (YesOrNoEnum.NO.getCode().equals(saveDto.getIsAnonymous())) {
                //非匿名,举报人信息不能为空
                List<ReportPersonInfo> reportPersonInfos = saveDto.getReportPersonInfos();
                if (ObjectUtils.isEmpty(reportPersonInfos)) {
                    throw new BusinessException("举报人信息不能为空");
                }
                reportPersonInfos.forEach(e -> {
                    if (PartyTypeEnum.PERSON.getCode().equals(e.getReportPersonType())) {
                        if (ObjectUtils.isEmpty(e.getReportPersonName()) || ObjectUtils.isEmpty(e.getContactPhone())) {

                            throw new BusinessException("举报人为个人时,姓名及联系电话不能为空");
                        }
                    } else if (PartyTypeEnum.LEGAL.getCode().equals(e.getReportPersonType())) {
                        if (ObjectUtils.isEmpty(e.getReportPersonName()) || ObjectUtils.isEmpty(e.getLegalRepresentName())
                                || ObjectUtils.isEmpty(e.getContactPhone())) {

                            throw new BusinessException("举报人为单位时,姓名、法定代表人（负责人）及联系电话不能为空");
                        }
                    } else {
                        throw new BusinessException("举报人类型有误");
                    }
                });

            }
            caseSourceDesc = JSON.toJSONString(saveDto.getReportPersonInfos());

        } else if (CaseSourceEnum.CASE_SOURCE_SJXZJGJB.getCode().equals(case_source)
                || CaseSourceEnum.CASE_SOURCE_XJXZJGBQ.getCode().equals(case_source)
                || CaseSourceEnum.CASE_SOURCE_YGBMYS.getCode().equals(case_source)) {
            //部门移送/上级行政机关交办/下级行政机关报请采集信息
            CaseSourceOrgInfo caseSourceOrgInfo = saveDto.getCaseSourceOrgInfo();
            if (ObjectUtils.isEmpty(caseSourceOrgInfo)) {
                throw new BusinessException("案件来源指定采集信息不能为空");
            }
            //名称,联系人,联系电话不能为空
            if (ObjectUtils.isEmpty(caseSourceOrgInfo.getOrgName()) || ObjectUtils.isEmpty(caseSourceOrgInfo.getContactName())
                    || ObjectUtils.isEmpty(caseSourceOrgInfo.getContactTel())) {
                throw new BusinessException("名称,联系人,联系电话不能为空");
            }
            caseSourceDesc = JSON.toJSONString(caseSourceOrgInfo);

        }

        mainInfo.setCaseSourceDesc(caseSourceDesc);
        //设置案源主表当事人名称
        String caseSourcePartyName = caseSourcePartyInfoService.getCaseSourcePartyName(saveDto.getCaseSourceId());
        mainInfo.setPartyName(caseSourcePartyName);
        //创建人id(浙政钉id)处理 获取用户id及
        String userDingId = saveDto.getCreateUserId();
        //调用执法平台接口获取用户信息
        if (!ObjectUtils.isEmpty(userDingId)) {
            //调用执法平台接口获取用户信息
            try {
                DingUserResultDto dingUserDto = xzzfInterfaceService.getUserByZwdAccountId(userDingId);
                if (!ObjectUtils.isEmpty(dingUserDto)) {
                    mainInfo.setCreateUserId(dingUserDto.getUserId().toString());
                    mainInfo.setCreateUserZwdingId(saveDto.getCreateUserId());
                }
            } catch (Exception exception) {
                log.error("根据id获取用户信息失败");
            }
        }

        //用户机构信息处理
        String createUserOrgUniscid = saveDto.getCreateUserOrgUniscid();
        //调用执法平台接口获取机构信息
        OrgInfoResultDto orgInfoResultDto = xzzfInterfaceService.getOrgInfoByUnicode(createUserOrgUniscid);
        if (ObjectUtils.isEmpty(orgInfoResultDto)) {
            throw new BusinessException("机构不存在--统一社会信用代码:【"+ saveDto.getCreateUserOrgUniscid() +"】");
        }
        mainInfo.setCreateUserOrgCode(orgInfoResultDto.getOrgCode());
        mainInfo.setCreateUserOrgName(orgInfoResultDto.getOrgName());

        mainInfo.setRegisterTime(new Date());
        mainInfo.setCreateTime(new Date());
        mainInfo.setId(saveDto.getCaseSourceId());
        mainInfo.setCaseSourceAppServiceId(saveDto.getCaseSourceRegisterId());
        //添加busiParamId
        mainInfo.setBusiParamId(caseSourceRegisterMainInfoService.getBusiParamId(saveDto.getLineCode(),orgInfoResultDto.getAreaCode()));

       /* //todo
        if(ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(saveDto.getCaseSourceAppId())){*/
            mainInfo.setCaseSourceAppActsCode(saveDto.getCaseSourceAppActsCode());
        //}
        if (isSave) {
            caseSourceRegisterMainInfoMapper.insertSelective(mainInfo);
        } else {
            caseSourceRegisterMainInfoMapper.updateByPrimaryKeySelective(mainInfo);
        }

    }

    /**
     * 检查数据处理
     */
    private void dealCaseSourceCheckInfo(CaseSourceRegisterOfAppSaveDto saveDto) {
        //检查或部门移送时检查数据非空时
        CaseSourceRegisterCheckInfoSaveDto checkInfo = saveDto.getCheckInfo();
        if (CaseSourceEnum.CASE_SOURCE_ZXZJCZFX.getCode().equals(saveDto.getCaseSource())
                || (CaseSourceEnum.CASE_SOURCE_YGBMYS.getCode().equals(saveDto.getCaseSource()) && !ObjectUtils.isEmpty(checkInfo))) {
            //检查数据校验
            if (ObjectUtils.isEmpty(checkInfo)) {
                throw new BusinessException("检查详情不能为空");
            }
            CustomCheckParamUtil.doCheck(checkInfo);
            //校验检查点内容信息
            List<CaseSourceRegisterCheckContentSaveDto> checkPositionContentList = checkInfo.getCheckPositionContentList();
            if (ObjectUtils.isEmpty(checkPositionContentList)) {
                throw new BusinessException("检查点内容不能为空");
            }
            checkPositionContentList.forEach(check -> {
                CustomCheckParamUtil.doCheck(check);
            });

            //删除检查数据
            Example del = new Example(CaseSourceRegisterDetailInfo.class);
            del.createCriteria().andEqualTo("caseSourceId", saveDto.getCaseSourceId());
            caseSourceRegisterDetailInfoMapper.deleteByExample(del);

            //新增数据
            CaseSourceRegisterDetailInfo detailInfo = new CaseSourceRegisterDetailInfo();
            BeanUtils.copyProperties(checkInfo, detailInfo);
            //检查时间处理
            try {
                detailInfo.setCheckTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(checkInfo.getCheckTime()));
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("检查时间格式错误,应为yyyy-MM-dd HH:mm:ss, 实际为:" + checkInfo.getCheckTime());
            }
            detailInfo.setId(BaseUtil.createUid());
            detailInfo.setCaseSourceId(saveDto.getCaseSourceId());
            //检查附件处理--不需要移送
            /*if (!ObjectUtils.isEmpty(checkPositionContentList)) {
                //删除之前的附件
                Example delExample = new Example(CaseSourceMaterialRecord.class);
                delExample.createCriteria().andEqualTo("caseSourceId", saveDto.getCaseSourceId());
                caseSourceMaterialRecordMapper.deleteByExample(delExample);

                checkPositionContentList.forEach(e -> {
                    List<String> docUrlList = e.getDocUrlList();
                    if (!ObjectUtils.isEmpty(docUrlList)) {
                        for (String s : docUrlList) {
                            CaseSourceMaterialRecord record = new CaseSourceMaterialRecord();
                            record.setCaseSourceId(saveDto.getCaseSourceId());
                            record.setEvidenceCode("OTHER");
                            record.setMaterialUrl(s);
                            record.setId(BaseUtil.createUid());
                            record.setUploadTime(LocalDateTime.now());
                            record.setIsDelete(Constant.STRING_0);
                            caseSourceMaterialRecordMapper.insertSelective(record);
                        }
                    }
                });
            }*/
            //检查点内容处理
            String checkPositionContent = JSONArray.toJSONString(checkInfo.getCheckPositionContentList());
            detailInfo.setCheckPositionContent(checkPositionContent);
            caseSourceRegisterDetailInfoMapper.insertSelective(detailInfo);

        }
    }

    /**
     * 案由数据处理
     *
     * @param saveDto
     */
    private void dealCaseSourceReasonInfo(CaseSourceRegisterOfAppSaveDto saveDto) {
        List<CaseReasonInfoOfAppDto> caseReasonInfoList = saveDto.getCaseReasonInfoList();
        if (!ObjectUtils.isEmpty(caseReasonInfoList)){
            //之前老数据更新为失效
            Example example = new Example(CaseReasonMainRecord.class);
            example.createCriteria().andEqualTo("caseId", saveDto.getCaseSourceId());
            List<CaseReasonMainRecord> recordList = caseReasonMainRecordMapper.selectByExample(example);
            if (recordList != null && recordList.size() > 0) {
                for (CaseReasonMainRecord record : recordList) {
                    record.setStatus(Constant.STRING_0);
                    caseReasonMainRecordMapper.updateByPrimaryKey(record);
                }
            }
            for (CaseReasonInfoOfAppDto caseReasonInfoDto : caseReasonInfoList) {

                CaseReasonMainRecord caseReasonMainRecord = new CaseReasonMainRecord();
                BeanUtils.copyProperties(caseReasonInfoDto, caseReasonMainRecord);
                caseReasonMainRecord.setCreateTime(LocalDateTime.now());
                caseReasonMainRecord.setId(BaseUtil.createUid());
                caseReasonMainRecord.setCaseId(saveDto.getCaseSourceId());
                caseReasonMainRecord.setCaseReasonNameSimple(BaseUtil.handleCaseReason(caseReasonInfoDto.getCaseReasonName()));
                caseReasonMainRecord.setIllegalBasisFormat(BaseUtil.removeHtml(caseReasonInfoDto.getIllegalBasis()));
                caseReasonMainRecord.setIllegalDetailFormat(BaseUtil.removeHtml(caseReasonInfoDto.getIllegalDetail()));
                caseReasonMainRecord.setPunishBasisFormat(BaseUtil.removeHtml(caseReasonInfoDto.getPunishBasis()));
                caseReasonMainRecord.setPunishDetailFormat(BaseUtil.removeHtml(caseReasonInfoDto.getPunishDetail()));
                caseReasonMainRecord.setStatus(Constant.STRING_1);
                //事项父级id处理
                //调用接口查询父级Id
                String caseReasonId = caseReasonInfoDto.getCaseReasonId();
                Result listCataIdResult = regulatoryService.getListCataIdByBusId(caseReasonId);
                String parentNodeId = "";
                if (HttpStatus.HTTP_OK == listCataIdResult.getCode()) {
                    parentNodeId = listCataIdResult.getData().toString();
                }

                String nodeIds = parentNodeId + "," + caseReasonId;
                caseReasonMainRecord.setCaseReasonNodeid(nodeIds);
                caseReasonMainRecordMapper.insertSelective(caseReasonMainRecord);
            }
        }
    }

    /**
     * 证据附件处理
     *
     * @param saveDto
     */
    public void dealCaseSourceMaterialRecord(CaseSourceRegisterOfAppSaveDto saveDto) {
        List<CaseSourceEvidenceDto> evidenceList = saveDto.getEvidenceList();
        if (!ObjectUtils.isEmpty(evidenceList)) {
            //删除之前证据
            Example updateExample = new Example(CaseSourceMaterialRecord.class);
            updateExample.createCriteria().andEqualTo("caseSourceId", saveDto.getCaseSourceId()).andEqualTo("isDelete", Constant.STRING_0);
            List<CaseSourceMaterialRecord> caseSourceMaterialRecords = caseSourceMaterialRecordMapper.selectByExample(updateExample);
            if (!ObjectUtils.isEmpty(caseSourceMaterialRecords)) {
                caseSourceMaterialRecords.forEach(e -> {
                    e.setIsDelete(Constant.STRING_1);
                    caseSourceMaterialRecordMapper.updateByPrimaryKeySelective(e);
                });
            }

            //证据列表
            evidenceList.forEach(e -> {
                String evidenceCode = e.getEvidenceCode();
                List<CaseSourceEvidenceAnnexDto> annexList = e.getAnnexList();
                if (!ObjectUtils.isEmpty(annexList)) {
                    for (CaseSourceEvidenceAnnexDto annexDto : annexList) {
                        //来源类型
                        String fileSourceType = annexDto.getFileSourceType();
                        CaseSourceMaterialRecord record = new CaseSourceMaterialRecord();
                        record.setCaseSourceId(saveDto.getCaseSourceId());
                        record.setEvidenceCode(evidenceCode);
                        record.setMaterialName(annexDto.getFileName());
                        record.setId(BaseUtil.createUid());
                        record.setIsDelete(Constant.STRING_0);
                        if (Constant.STRING_2.equals(fileSourceType) || Constant.STRING_1.equals(fileSourceType)) {//完整路径附件
                            String path = annexDto.getFilePath();
                            record.setMaterialUrl(path);
                        } else if (Constant.STRING_3.equals(fileSourceType)){//证据中心
                            record.setEvidenceUid(annexDto.getEvidenceUid());
                            record.setEvidenceLinkType(annexDto.getEvidenceLinkType());
                        }
                        record.setUploadTime(LocalDateTime.now());
                        caseSourceMaterialRecordMapper.insertSelective(record);
                    }
                }
            });
        }

    }

    /**
     * 案源参数校验
     *
     * @param saveDto
     */
    private void checkCaseSourceParams(CaseSourceRegisterOfAppSaveDto saveDto) {
        //校验当前案源是否存在
        Example query = new Example(CaseSourceRegisterMainInfo.class);
        query.createCriteria().andEqualTo("caseSourceAppServiceId", saveDto.getCaseSourceRegisterId()).andEqualTo("caseSourceAppId", saveDto.getCaseSourceAppId());
        List<CaseSourceRegisterMainInfo> caseSourceRegisterMainInfos = caseSourceRegisterMainInfoMapper.selectByExample(query);
        if (!ObjectUtils.isEmpty(caseSourceRegisterMainInfos)) {
            CaseSourceRegisterMainInfo mainInfo = caseSourceRegisterMainInfos.get(0);
            //登记操作,案源状态不为待分派时不允许更新
            if (CaseSourceOperateTypeEnum.REGISTER.getCode().equals(saveDto.getCaseSourceOperateType())
                    && !CaseSourceStatusEnum.TO_DISPATCH.getIndex().equals(mainInfo.getCaseSourceStatus())) {
                throw new BusinessException("案源【"+ saveDto.getCaseSourceRegisterId() +"】已存在且已处于"
                        + CaseSourceStatusEnum.getValue(mainInfo.getCaseSourceStatus()) + "状态");
            }
            //案源指派,案源状态不为预调查时不允许更新
            if (CaseSourceOperateTypeEnum.APPOINT.getCode().equals(saveDto.getCaseSourceOperateType())
                    && !CaseSourceStatusEnum.PRE_SURVEY.getIndex().equals(mainInfo.getCaseSourceStatus())) {
                throw new BusinessException("案源【"+ saveDto.getCaseSourceRegisterId() +"】已存在且已处于"
                        + CaseSourceStatusEnum.getValue(mainInfo.getCaseSourceStatus()) + "状态");
            }
        }

        //案源操作类型校验
        if (!CaseSourceOperateTypeEnum.isLegalEnumCode(saveDto.getCaseSourceOperateType())) {
            throw new BusinessException("案件操作类型有误");
        }
        //案件来源校验
        /*if (!CaseSourceEnum.isLegalEnumCode(saveDto.getCaseSource())) {
            throw new BusinessException("案件来源有误");
        }*/
        //当事人校验
        /*List<CaseSourcePartyInfoSaveDto> caseSourcePartyInfoDtoList = saveDto.getCaseSourcePartyInfoDtoList();
        if (!ObjectUtils.isEmpty(caseSourcePartyInfoDtoList)) {
            caseSourcePartyInfoDtoList.forEach(party -> {
                String partyType = party.getPartyType();
                if (ObjectUtils.isEmpty(partyType)) {
                    throw new BusinessException("当事人类型不能为空");
                }
                //个人参数校验
                //个人情况下必填字段1、姓名；2、身份证件类型3、证件号码4、出生年月；5、性别；6、住址
                if (PartyTypeEnum.PERSON.getCode().equals(partyType) &&
                        (ObjectUtils.isEmpty(party.getPartyName()) || ObjectUtils.isEmpty(party.getPartyIdentityType())
                                || ObjectUtils.isEmpty(party.getPartyIdentityCode()) || ObjectUtils.isEmpty(party.getPersonBirth())
                                || ObjectUtils.isEmpty(party.getPersonSex()) || ObjectUtils.isEmpty(party.getAddressDetail()))) {
                    throw new BusinessException("请完善当事人(个人)信息");
                }

                //单位参数校验
                //单位情况下必填字段1、名称；2、法定代表人（负责人）3、社会信用代码；4、住址；5、单位类型
                if (PartyTypeEnum.LEGAL.getCode().equals(partyType) &&
                        (ObjectUtils.isEmpty(party.getPartyName()) || ObjectUtils.isEmpty(party.getLegalName())
                                || ObjectUtils.isEmpty(party.getPartyIdentityCode()) || ObjectUtils.isEmpty(party.getAddressDetail())
                                || ObjectUtils.isEmpty(party.getEntType()))) {
                    throw new BusinessException("请完善当事人(单位)信息");
                }
            });
        }*/

        //办案人员校验
        String caseSourceOperateType = saveDto.getCaseSourceOperateType();
        if (CaseSourceOperateTypeEnum.APPOINT.getCode().equals(caseSourceOperateType)) {
            //案源指派,办案人信息不能为空
            if (ObjectUtils.isEmpty(saveDto.getHandleOrgCode())) {
                throw new BusinessException("办案机构编码不能为空");
            }
            if (ObjectUtils.isEmpty(saveDto.getHandleOrgName())) {
                throw new BusinessException("办案机构名称不能为空");
            }
            if (ObjectUtils.isEmpty(saveDto.getHandlePersonMainId())) {
                throw new BusinessException("主办人员id不能为空");
            }
            if (ObjectUtils.isEmpty(saveDto.getHandlePersonMainName())) {
                throw new BusinessException("主办人员名称不能为空");
            }
            if (ObjectUtils.isEmpty(saveDto.getHandlePersonAssistId())) {
                throw new BusinessException("协办人员id不能为空");
            }
            if (ObjectUtils.isEmpty(saveDto.getHandlePersonAssistName())) {
                throw new BusinessException("协办人员名称不能为空");
            }
            //条线信息不能为空
            if (ObjectUtils.isEmpty(saveDto.getLineCode()) || ObjectUtils.isEmpty(saveDto.getLineName())) {
                throw new BusinessException("案源指派时,条线信息不能为空");
            }
        }

    }

    /**
     * 流转日志保存
     *
     * @param saveDto
     */
    private void saveCaseSourceFlowRecord(CaseSourceRegisterOfAppSaveDto saveDto){
        //流转日志保存 案源立案
        CaseSourceFlowRecord lastCaseSourceFlowRecord = caseSourceFlowRecordService.getLastCaseSourceFlowRecord(saveDto.getCaseSourceId());
        if (!ObjectUtils.isEmpty(lastCaseSourceFlowRecord) && !ObjectUtils.isEmpty(lastCaseSourceFlowRecord.getCaseSourceId())) {
            return;
        }
        Date date = new Date();
        FlowCommonDto dto=new FlowCommonDto();
        dto.setCaseSourceId(saveDto.getCaseSourceId());
        dto.setFlowStartTime(date);
        dto.setFlowEndTime(date);
        dto.setStartPersonName(saveDto.getCreateUserName());
        dto.setStartPersonOrgName(saveDto.getCreateUserOrgName());
        dto.setStartPersonDeptName(saveDto.getCreateUserDeptName());
        dto.setFlowStageType(Constant.CASE_SOURCE_STAGE_AYDJ);
        caseSourceFlowRecordService.saveCommonFlowRecord(dto);
        if(StringUtils.isNotBlank(saveDto.getHandlePersonMainId())){
            //如果已指派  生成指派流转日志
            //指派时间增加一秒
            date.setTime(date.getTime() + 1000);
            dto.setFlowStartTime(date);
            dto.setFlowEndTime(date);
            dto.setFlowStageType(Constant.CASE_SOURCE_STAGE_AYZP);
            List<AppointedPersonInfo> appointedPersonInfos=new ArrayList<>();
            AppointedPersonInfo appointedMainPersonInfo=new AppointedPersonInfo();
            appointedMainPersonInfo.setPersonName(saveDto.getHandlePersonMainName());
            appointedMainPersonInfo.setPersonOrgName(saveDto.getHandleOrgName());
            appointedMainPersonInfo.setPersonDeptName(saveDto.getHandleDeptName());
            appointedPersonInfos.add(appointedMainPersonInfo);
            AppointedPersonInfo appointedAssistPersonInfo=new AppointedPersonInfo();
            appointedAssistPersonInfo.setPersonName(saveDto.getHandlePersonAssistName());
            appointedAssistPersonInfo.setPersonOrgName(saveDto.getHandleOrgName());
            appointedAssistPersonInfo.setPersonDeptName(saveDto.getHandleDeptName());
            appointedPersonInfos.add(appointedAssistPersonInfo);
            dto.setAppointedPersonInfoList(appointedPersonInfos);
            caseSourceFlowRecordService.saveCommonFlowRecord(dto);
        }
    }


    /**
     * 描述： 外部应用立案保存
     *
     * @author: zhengqiang
     * @date: 2022/8/15
     * @param: saveDto
     * @return {@link Result}
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveCaseRegisterOfApp(CaseRegisterOfAppSaveDto saveDto) {
        log.info("立案登记saveCaseRegisterOfApp 请求参数:{}", JSON.toJSONString(saveDto));
        UserDTO userInfo = UserUtil.getUserInfo();

        CaseRegisterSaveDto caseRegisterSaveDto = new CaseRegisterSaveDto();
        BeanUtils.copyProperties(saveDto, caseRegisterSaveDto);
        caseRegisterSaveDto.setCaseType(CaseTypeEnum.NORMAL_PROCEDURE.getCode());
        //案由信息处理
        List<CaseReasonInfoDto> reasonList = new ArrayList<>();
        List<CaseReasonInfoOfAppDto> caseReasonInfoOfAppList = saveDto.getCaseReasonInfoList();
        if (!ObjectUtils.isEmpty(caseReasonInfoOfAppList)) {
            for (int i = 0; i < caseReasonInfoOfAppList.size(); i++) {
                CaseReasonInfoDto reasonInfoDto = new CaseReasonInfoDto();
                CaseReasonInfoOfAppDto caseReasonInfoOfAppDto = caseReasonInfoOfAppList.get(i);
                //案由参数校验
                CustomCheckParamUtil.doCheck(caseReasonInfoOfAppDto);
                BeanUtils.copyProperties(caseReasonInfoOfAppDto, reasonInfoDto);
                /*if (i == 0) {
                    //领域及条线信息处理
                    caseRegisterSaveDto.setCaseTerritoryCode(caseReasonInfoOfAppDto.getTerritoryCode());
                    caseRegisterSaveDto.setCaseTerritoryName(caseReasonInfoOfAppDto.getTerritoryName());
                    caseRegisterSaveDto.setLineCode(caseReasonInfoOfAppDto.getLineCode());
                    caseRegisterSaveDto.setLineName(caseReasonInfoOfAppDto.getLineName());
                }*/
                //调用接口查询父级Id
                String caseReasonId = caseReasonInfoOfAppDto.getCaseReasonId();
                Result listCataIdResult = regulatoryService.getListCataIdByBusId(caseReasonId);
                String parentNodeId = "";
                if (HttpStatus.HTTP_OK == listCataIdResult.getCode()) {
                    parentNodeId = listCataIdResult.getData().toString();
                }
                String[] caseReasonIds = {parentNodeId, caseReasonId};
                reasonInfoDto.setCaseReasonIds(caseReasonIds);
                reasonInfoDto.setWasPlus(true);
                reasonInfoDto.setSortNo(i+1);
                reasonList.add(reasonInfoDto);
            }
            caseRegisterSaveDto.setCaseReasonInfoList(reasonList);
        }

        //当事人数据处理
        if (caseRegisterSaveDto.getPartiesLegalInfoList() == null) {
            caseRegisterSaveDto.setPartiesLegalInfoList(new ArrayList<>());
        }
        if (caseRegisterSaveDto.getPartiesPersonInfoList() == null) {
            caseRegisterSaveDto.setPartiesPersonInfoList(new ArrayList<>());
        }
        //附件处理
        List<AppendixDto> appendixList = caseRegisterSaveDto.getAppendixList();
        if (!ObjectUtils.isEmpty(appendixList)) {
            appendixList.forEach(e -> {
                String appendixUrl = e.getAppendixUrl();
                if (!ObjectUtils.isEmpty(appendixUrl) && appendixUrl.contains("taskCenter")) {
                    //检查照片转存
                    String newUrl = appendixUrl.replace("http://183.230.113.144:41130", taskCenterUrl);
                    byte[] bytes = HttpUtil.createGet(newUrl).execute().bodyBytes();
                    //上传oss
                    FileInfoSaveDto fileInfo = new FileInfoSaveDto();
                    fileInfo.setFileBytes(bytes);
                    fileInfo.setFileTransferForm(FileTransferFormEnum.FILE_TRANSFER_FORM_3.getCode());
                    fileInfo.setFileType(AttachmentRequestContentTypeEnum.png.getCode());
                    Result result = iOssOperateService.uploadFile(fileInfo);
                    if (!ObjectUtils.isEmpty(result) && HttpStatus.HTTP_OK == result.getCode()
                            && !ObjectUtils.isEmpty(result.getData())) {
                        String ossUrl = result.getData().toString();
                        e.setAppendixUrl(ossUrl);
                    }
                }
                e.setAppendixTypeId(AttachmentTypeEnum.OTHER_EVIDENCE.getCode());
                if (ObjectUtils.isEmpty(e.getAppendixName())) {
                    e.setAppendixName("现场照片");
                }
            });
        }

        //证据列表处理
        List<CaseSourceEvidenceDto> evidenceList = saveDto.getEvidenceList();
        if (!ObjectUtils.isEmpty(evidenceList)) {
            evidenceList.forEach(e -> {
                List<CaseSourceEvidenceAnnexDto> annexList = e.getAnnexList();
                if (!ObjectUtils.isEmpty(annexList)) {
                    for (CaseSourceEvidenceAnnexDto annexDto : annexList) {
                        //来源类型
                        String fileSourceType = annexDto.getFileSourceType();
                        AppendixDto appendixDto = new AppendixDto();
                        appendixDto.setAppendixTypeId(AttachmentTypeEnum.OTHER_EVIDENCE.getCode());
                        String fileName = annexDto.getFileName();
                        if (ObjectUtils.isEmpty(fileName)) {
                            fileName = AttachmentTypeEnum.OTHER_EVIDENCE.name();
                        }
                        appendixDto.setAppendixName(fileName);
                        appendixDto.setAppendixType(AttachmentTypeEnum.OTHER_EVIDENCE.getDes());

                        if (Constant.STRING_2.equals(fileSourceType)) {//完整路径附件
                            appendixDto.setAppendixUrl(annexDto.getFilePath());
                        } else if (Constant.STRING_3.equals(fileSourceType)){//证据中心
                            //调用证据接口获取预览地址
                            String evidenceLink = evidenceInventoryService.getEvidenceLink(annexDto.getEvidenceUid(), annexDto.getEvidenceLinkType());
                            appendixDto.setAppendixUrl(evidenceLink);
                        }
                        appendixList.add(appendixDto);
                    }
                }
            });
        }
        //条线数据处理
        List<LineTerritoryInfoVo> lineTerritoryInfoVos = sysDepartParamService.getLineInfoListByOrgCode(userInfo.getOrgCode());
        //暂时取第一个条线
        lineTerritoryInfoVos = lineTerritoryInfoVos.stream().filter(e -> Constant.STRING_1.equals(e.getLineCaseHandleStatusCode())).collect(Collectors.toList());
        LineTerritoryInfoVo lineTerritoryInfoVo = lineTerritoryInfoVos.get(0);
        //领域及条线信息处理
        caseRegisterSaveDto.setCaseTerritoryCode(lineTerritoryInfoVo.getTerritoryCode());
        caseRegisterSaveDto.setCaseTerritoryName(lineTerritoryInfoVo.getTerritoryName());
        caseRegisterSaveDto.setLineCode(lineTerritoryInfoVo.getLineCode());
        caseRegisterSaveDto.setLineName(lineTerritoryInfoVo.getLineName());

        if (!ObjectUtils.isEmpty(saveDto.getCheckTaskNumber())) {
            //保存检查信息
            Example del = new Example(CaseSourceRegisterDetailInfo.class);
            del.createCriteria().andEqualTo("caseSourceId", saveDto.getCaseSourceRegisterId());
            caseSourceRegisterDetailInfoMapper.deleteByExample(del);
            //新增数据
            CaseSourceRegisterDetailInfo detailInfo = new CaseSourceRegisterDetailInfo();
            BeanUtils.copyProperties(saveDto, detailInfo);
            detailInfo.setId(BaseUtil.createUid());
            detailInfo.setCaseSourceId(saveDto.getCaseSourceRegisterId());
            caseSourceRegisterDetailInfoMapper.insertSelective(detailInfo);
        }
        //检查转处罚设置caseId与检查业务id一致
        caseRegisterSaveDto.setCaseId(saveDto.getCaseSourceRegisterId());
        //校验案件是否已存在
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseSourceRegisterId());
        if (ObjectUtil.isNotEmpty(caseMainInfo)
                && !CaseStatusEnum.TEMP.getCode().equals(caseMainInfo.getCaseStatus())) {
            throw new BusinessException("案件已存在（"+ saveDto.getCaseSourceRegisterId() +"）, 已处于"+ caseMainInfo.getCaseCurrentLinkName() +"环节!");
        }

        int i = caseRegisterService.saveCaseRegisterTemporary(caseRegisterSaveDto);
        if (i > 0) {
            return Result.success(Constant.STRING_SAVE_SUCCESS);
        }
        return Result.error(Constant.STRING_SAVE_FAIL);
    }

}
